import store from '@/stores/index.js'
const baseURL = 'https://api.micaitongcheng.com/api'
//拦截器
const httpInterceptor = {
	//拦截前
	invoke(options) {
		//非http 开头需拼接地址
		if(!options.url.startsWith('http')) {
			options.url = baseURL + options.url
		}
		//请求超时
		options.timeout = 10000
		//添加小程序端请求头标识
		options.header = {
		  ...options.header,
		  'source-client': 'miniapp',
		  'Authori-zation':'Bearer '+ store.state.token//配置token
		  
		}
	}
}
uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFile', httpInterceptor)

//请求拦截
export const http = (options) => {
	//返回Promise对象
	return new Promise((resolve,reject) =>{
		uni.request({
			...options,
			//响应成功
			success(res) {
				if(res.statusCode >= 200 && res.statusCode < 300) {
					resolve(res.data)
					if(res.data.status === 400){
						uni.showToast({
							title:res.data.msg,
							icon:'error'
						})
					}
					if(res.data.status === 0){
						uni.showToast({
							title:res.data.msg,
							icon:'error'
						})
					}
					if(res.data.status === 110002 || res.data.status === 110003) {
						let pageurl = getCurrentPages()
						if(pageurl[0].route != 'pages/orders/orders'){
							// 110002,110003错误 跳回登录页
							store.commit('deletetoken')
							uni.reLaunch({
								url:'/page_login/index'
							})
							reject(res)
						}
					}
				}
			},
			fail(err) {
				uni.showToast({
					icon:'none',
					title:'网络错误,换个网络试试'
				})
			}
		})
	})
}
export default http